#include "BlockQueue.hpp"
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
#include <ctime>
#include "Task.hpp"

class ThreadData
{
public:
    ThreadData(const std::string &name, BlockQueue<Task> *bq) : _name(name), _bq(bq)
    {
    }
    std::string _name;
    BlockQueue<Task> *_bq;
};

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        int data1 = rand() % 10;
        usleep(rand() % 123);
        int data2 = rand() % 10;
        usleep(rand() % 123);
        char oper = opers[rand() % (opers.size())];
        Task t(data1, data2, oper);
        std::cout << "productor task: " << t.PrintTask() << std::endl;
        td->_bq->Push(t);
    }
    return nullptr;
}

void *Consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        Task t;
        bq->Pop(&t);
        t();
        std::cout << "consumer data: " << t.PrintResult() << std::endl;
    }
    return nullptr;
}

int main()
{
    srand((uint16_t)time(nullptr) ^ getpid() ^ pthread_self());
    BlockQueue<Task> *bq = new BlockQueue<Task>;
    pthread_t c[3], p[2];
    ThreadData *td = new ThreadData("thread-0", bq);
    pthread_create(&p[0], nullptr, Productor, (void *)td);

    ThreadData *td1 = new ThreadData("thread-1", bq);
    pthread_create(&p[1], nullptr, Productor, (void *)td1);

    ThreadData *td2 = new ThreadData("thread-2", bq);
    pthread_create(&p[2], nullptr, Productor, (void *)td2);

    pthread_create(&c[0], nullptr, Consumer, (void *)bq);
    pthread_create(&c[1], nullptr, Consumer, (void *)bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    return 0;
}